using System;
using System.Collections.Specialized;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;

namespace Framework.Library.Core.Utils.Collections
{
    [Serializable]
    public sealed class SerializableNameValueCollection : NameValueCollection, IXmlSerializable
    {
        #region IXmlSerializable Members

        XmlSchema IXmlSerializable.GetSchema()
        {
            return null;
        }

        void IXmlSerializable.ReadXml(XmlReader reader)
        {
            // name start
            reader.Read();

            while (reader.Name == "NameValue")
            {
                string name;
                string value;

                // Name
                reader.Read();
                reader.Read();
                name = reader.Value;
                reader.Read();

                // Value
                reader.Read();
                reader.Read();
                value = reader.Value;
                reader.Read();

                reader.Read();
                reader.Read();

                Add(name, value);
            }

            // name end
            reader.Read();
        }

        void IXmlSerializable.WriteXml(XmlWriter writer)
        {
            foreach (string key in Keys)
            {
                writer.WriteStartElement("NameValue");
                writer.WriteElementString("Name", key);
                writer.WriteElementString("Value", this[key]);
                writer.WriteEndElement();
            }
        }

        #endregion
    }
}